﻿using System;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using Kele.Activity.Core;
using Kele.Activity.Models;
using MySql.Data.MySqlClient;

namespace Kele.Activity
{
    public class UserService
    {
        private readonly string _connectionString = AppConfig.Setting.DefaultConnectionString;

        public async Task UpdateUserAsync(User user, string state)
        {
            using (var connection = new MySqlConnection(_connectionString))
            {
           
                user.created = user.modified = DateTime.Now;
                var sql = new StringBuilder();
                sql.Append(" update kl_user set")
                    .Append(" city = @city, country = @country, avatar = @headimgurl, nick = @nick, province = @province,")
                    .Append(" sex = @sex, unionid = @unionid, state = @state, modified = @modified")
                    .Append(" where openid = @openid");
                var i = await connection.ExecuteAsync(sql.ToString(), user);
                if (i == 0)
                {
                    sql.Clear();
                    sql.Append(" INSERT INTO kl_user(city, country,avatar,nick,openid,province,sex,unionid,state, created,modified)")
                        .Append(" VALUES(@city, @country,@headimgurl,@nick,@openid,@province,@sex,@unionid,@state, @created,@modified)");
                    await connection.ExecuteAsync(sql.ToString(), user);
                }
            }
        }
        public async Task<dynamic> GetUserByStateAsync(string state)
        {
            using (var connection = new MySqlConnection(_connectionString))
            {
                const string sql = "SELECT openid,unionid,nick avatar FROM `kl_user` where state=@state";
                return await connection.QueryFirstOrDefaultAsync(sql, new { state });
            }
        }



        //public async Task UpdateUser(User user, string state)
        //{
        //    using (var con = new MySqlConnection(_connectionString))
        //    {
        //        var sql = new StringBuilder();
        //        var val = con.ExecuteScalar<string>("select openId from kl_user where openid=@openid", new { user.openid });
        //        if (string.IsNullOrEmpty(val))
        //        {
        //            //创建用户
        //            user.created = user.modified = DateTime.Now;

        //            sql.Append(" INSERT INTO kl_user(city, country,headimgurl,nickname,openid,province,sex,unionid,state, created,modified)")
        //                .Append(" VALUES(@city, @country,@headimgurl,@nickname,@openid,@province,@sex,@unionid,@state, @created,@modified)");
        //            await con.ExecuteAsync(sql.ToString(), user);
        //            //var merchantProp = MearchantProp.Unregistered;
        //            ////创建商户
        //            //if (string.IsNullOrWhiteSpace(user.unionid)) merchantProp = MearchantProp.MpSubscribe;
        //            //sql.Clear();
        //            //sql.Append(" INSERT INTO kl_merchant(openid, unionid,merchant_prop,health)")
        //            //    .Append(" VALUES(@openid, @unionid,@merchantProp,@health)");
        //            //con.Execute(sql.ToString(), new{ user.openid,user.unionid, merchantProp,health =0});

        //        }
        //        else
        //        {
        //            //更新用户
        //            user.modified = DateTime.Now;
        //            sql.Clear();
        //            sql.Append(" update kl_user set")
        //               .Append(" city = @city, country = @country, headimgurl = @headimgurl, nickname = @nickname, province = @province,")
        //               .Append(" sex = @sex, unionid = @unionid, state = @state, modified = @modified")
        //               .Append(" where openid = @openid");
        //            await con.ExecuteAsync(sql.ToString(), user);
        //        }
        //    }
        //}

        public async Task<Merchant> GetMerchantByState(string state)
        {
            using (var con = new MySqlConnection(_connectionString))
            {
                const string sql = "select * from kl_merchant  m inner join kl_user u  on  m.openid = u.openid and  u.state=@state";
                var result = await con.QueryFirstOrDefaultAsync<Merchant>(sql, new { state });
                return result ?? new Merchant();
            }
        }
    
        public async Task UpdateUserState(string state, string newState)
        {
            using (var con = new MySqlConnection(_connectionString))
            {
                const string sql = "update kl_user set state = @newState where  state=@state";
                await con.ExecuteAsync(sql, new { state, newState });
            }
        }



        //public KeleUser FindByOpenId(string openId)
        //{
        //    try
        //    {
        //        using (var conn = new MySqlConnection(_connectionString))
        //        {
        //            var users = conn.Query<KeleUser>("select id from kl_user where state=@state", new { openId });
        //            return users.FirstOrDefault();
        //        }
        //    }
        //    catch (Exception)
        //    {
        //        return null;
        //    }
        //}

        //public KeleUser FindByUsername(string username)
        //{
        //    using (var conn = new MySqlConnection(_connectionString))
        //    {
        //        var users = conn.Query<KeleUser>(
        //            "select id, user_name,password,name,email,qq  from  kl_user where user_name=@user_name",
        //            new { user_name = username });
        //        return users.FirstOrDefault();
        //    }
        //}
    }
}